using BasicData.API.Application.Command;
using BasicData.API.Dtos;
using BasicData.Domain.Entities;
using BasicData.ErrorCode;
using BasicData.Infrastructure.Interfasce;
using MediatR;
using Microsoft.EntityFrameworkCore;
using System;
using System.Threading;
using System.Threading.Tasks;

namespace BasicData.API.Application.CommandHandlers
{
    /// <summary>
    /// 添加生产信息命令处理器
    /// </summary>
    public class AddProductionInfoCommandHandler : IRequestHandler<AddProductionInfoCommand, APIResult<ProductionInfoDTO>>
    {
        private readonly IBaseRepositroy<ProductionInfo> _productionInfoRepository;
        private readonly IBaseRepositroy<Goods> _goodsRepository;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="productionInfoRepository">生产信息仓储</param>
        /// <param name="goodsRepository">商品仓储</param>
        public AddProductionInfoCommandHandler(
            IBaseRepositroy<ProductionInfo> productionInfoRepository,
            IBaseRepositroy<Goods> goodsRepository)
        {
            _productionInfoRepository = productionInfoRepository;
            _goodsRepository = goodsRepository;
        }

        /// <summary>
        /// 处理添加生产信息命令
        /// </summary>
        /// <param name="request">命令请求</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>添加结果</returns>
        public async Task<APIResult<ProductionInfoDTO>> Handle(AddProductionInfoCommand request, CancellationToken cancellationToken)
        {
            try
            {
                // 验证商品是否存在
                var goods = await _goodsRepository.FirstOrDefaultAsync(g => g.GoodsId == request.GoodsId )
                    .FirstOrDefaultAsync(cancellationToken);
                
                if (goods == null)
                {
                    return new APIResult<ProductionInfoDTO>
                    {
                        Code = ResultCode.添加失败,
                        Message = $"商品ID为{request.GoodsId}的商品不存在，请先添加商品或检查商品ID是否正确"
                    };
                }

                // 验证批次号是否已存在
                var existingInfo = await _productionInfoRepository.FirstOrDefaultAsync(p => p.BatchNumber == request.BatchNumber && !p.IsDeleted)
                    .FirstOrDefaultAsync(cancellationToken);
                
                if (existingInfo != null)
                {
                    return new APIResult<ProductionInfoDTO>
                    {
                        Code = ResultCode.添加失败,
                        Message = $"批次号'{request.BatchNumber}'已存在，请使用其他批次号"
                    };
                }

                // 创建新的生产信息实体
                var productionInfo = new ProductionInfo
                {
                    Id = Guid.NewGuid(),
                    BatchNumber = request.BatchNumber,
                    ShelfLifeDays = request.ShelfLifeDays,
                    ProductionLicenseNumber = request.ProductionLicenseNumber,
                    ManufacturerName = request.ManufacturerName,
                    CoverImageUrl = request.CoverImageUrl,
                    GoodsId = request.GoodsId,
                    CreatedBy = request.CreatedBy ?? "System",
                    CreatedTime = DateTime.Now
                };

                // 添加到数据库
                await _productionInfoRepository.AddAsync(productionInfo);

                // 创建返回DTO
                var productionInfoDto = new ProductionInfoDTO
                {
                    Id = productionInfo.Id,
                    BatchNumber = productionInfo.BatchNumber,
                    ShelfLifeDays = productionInfo.ShelfLifeDays,
                    ProductionLicenseNumber = productionInfo.ProductionLicenseNumber,
                    ManufacturerName = productionInfo.ManufacturerName,
                    CoverImageUrl = productionInfo.CoverImageUrl,
                    GoodsId = productionInfo.GoodsId,
                    CreatedTime = productionInfo.CreatedTime,
                    ModifiedTime = productionInfo.ModifiedTime
                };

                // 返回成功结果
                return new APIResult<ProductionInfoDTO>
                {
                    Code = ResultCode.添加成功,
                    Message = "添加生产信息成功",
                    Data = productionInfoDto
                };
            }
            catch (Exception ex)
            {
                return new APIResult<ProductionInfoDTO>
                {
                    Code = ResultCode.添加失败,
                    Message = $"添加生产信息失败: {ex.Message}"
                };
            }
        }
    }
} 